package com.siyoumi.console.modules.sys.service;

import com.siyoumi.config.SysConfig;
import com.siyoumi.util.XHttpClient;
import com.siyoumi.util.XJson;
import com.siyoumi.util.XReturn;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class CmdApi {
    protected static String getApiRoot() {
        if (SysConfig.getIns().isDev()) {
            return "http://dev.x.siyoumi.com/";
        }
        return "https://app.lai-m.com/";
    }

    protected static String getApiUrl(String urlFix) {
        return getApiRoot() + urlFix;
    }

    public static XReturn getCmd() {
        String apiUrl = getApiUrl("app/sh/sh_api/cmd");
        return getApi(apiUrl);
    }

    //标记已完成
    public static XReturn cmdDone(String id, String returnMsg) {
        String apiUrl = getApiUrl("app/sh/sh_api/cmd_done?id=" + id);

        Map<String, String> postData = new HashMap<>();
        postData.put("id", id);
        postData.put("return_msg", returnMsg);
        return postFormApi(apiUrl, postData);
    }

    //标记运行中
    public static XReturn cmdRun(String id) {
        String apiUrl = getApiUrl("app/sh/sh_api/cmd_run?id=" + id);
        return getApi(apiUrl);
    }


    protected static XReturn postFormApi(String url, Map<String, String> postData) {
        XHttpClient client = XHttpClient.getInstance();
        String returnStr = client.postForm(url, null, postData);
        log.info("url: {}", url);
        log.info("post_data: {}", XJson.toJSONString(postData));
        log.info("return_str: {}", returnStr);

        return XReturn.parse(returnStr);
    }

    protected static XReturn getApi(String url) {
        XHttpClient client = XHttpClient.getInstance();
        String returnStr = client.get(url, null);
        log.info("url: {}", url);
        log.info("return_str: {}", returnStr);

        return XReturn.parse(returnStr);
    }
}
